//
//  StatisticViewController.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/12/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "StatisticViewController.h"
#import "ProductThumbView.h"
#import "ProductDetailViewControllerEx.h"
#import "DemoTableController.h"
#import "ShopViewController.h"
#import "FPPopoverController.h"
#import "TipView.h"
#import "DataManager.h"
#import "UIHelper.h"
#import "PictureViewController.h"
#import "PopupView.h"
#import "ProductObject.h"

#import "TKImageCache.h"
#import "AppManager.h"
#import "SizeObject.h"
#import "UserObject.h"
#import "SuitView.h"
#import "SuitThumbView.h"
#import "SuitDetailViewController.h"
#import "PMGlobal.h"
@interface StatisticViewController ()
{
    NSMutableArray *filterBtns_;
    
    NSArray *keyCategories_;
    
    
    TKImageCache *imageCache_;
}

@end

@implementation StatisticViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tag:(int)tag
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        numtag = tag;
        shop = [[DataManager sharedManager]getShopList];
        if (numtag == 1) {
            [self setNavTitle:@"订单管理"];
            
            UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
            UIImage *img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
            [b setBackgroundImage:img forState:UIControlStateNormal];
            b.frame = CGRectMake(10, 10, 106, 32);
            [b setTitle:@"手动提交订单" forState:UIControlStateNormal];
            b.titleLabel.font = [UIFont systemFontOfSize:12];
            [b addTarget:self action:@selector(submitbyself) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:b];
           // self.navigationItem.rightBarButtonItem = right;
            
            UIButton *b1 = [UIButton buttonWithType:UIButtonTypeCustom];
            [b1 setBackgroundImage:img forState:UIControlStateNormal];
            b1.frame = CGRectMake(700, 10, 106, 32);
            [b1 setTitle:@"复制到其他店铺" forState:UIControlStateNormal];
            b1.titleLabel.font = [UIFont systemFontOfSize:13];
            [b1 addTarget:self action:@selector(copytopaste) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *copy = [[UIBarButtonItem alloc] initWithCustomView:b1];
            
            UIButton *b2 = [UIButton buttonWithType:UIButtonTypeCustom];
            [b2 setBackgroundImage:img forState:UIControlStateNormal];
            b2.frame = CGRectMake(700, 10, 106, 32);
            [b2 setTitle:@"清除取消款" forState:UIControlStateNormal];
            b2.titleLabel.font = b1.titleLabel.font;
            [b2 addTarget:self action:@selector(removecancelled) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *removecancelled = [[UIBarButtonItem alloc] initWithCustomView:b2];
            
            NSArray *arr = [[NSArray alloc]initWithObjects:right,copy,removecancelled, nil];
            self.navigationItem.rightBarButtonItems = arr;
        }
        else
        {
            [self setNavTitle:@"我的收藏"];
        }
#ifdef DHH_iOS
        if (numtag == 1) {
        UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:[[UIHelper getInstance] getBundleImage:@"main_statistic_iphone.png"] tag:0];
        self.tabBarItem = tabBarItem;
        }
        else
        {
            UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:[[UIHelper getInstance] getBundleImage:@"main_collect_iphone.png"] tag:0];
            self.tabBarItem = tabBarItem;
        }
#endif
        
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ordernumrefresh:) name:@"ordernumrefresh" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showtip:) name:@"showtip" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statRefreshShop:) name:@"statRefreshShop" object:nil];
       // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss:) name:@"dismiss1" object:nil];
       // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hidden:) name:@"hidden" object:nil];
        if (numtag == 1) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(index2:) name:@"index2" object:nil];
        }
        else
        {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(index3:) name:@"index3" object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(suitFilterRefresh1:) name:@"suitFilterRefresh1" object:nil];
        }
        
        keyCategories_ = [[DataManager sharedManager] getKeyCategories];
        
        imageCache_ = [[TKImageCache alloc] initWithCacheDirectoryName:@"image"];
        imageCache_.notificationName = @"static_image";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(static_image:) name:@"static_image" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshstatistic:) name:@"refreshstatistic" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detail1:) name:@"detail1" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detail2:) name:@"goToProductDetail2" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ordernumrefresh1:) name:@"ordernumrefresh1" object:nil];
    }
    return self;
}

- (void)dealloc{
    [imageCache_ cancelOperations];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    KeyFilter = [[NSMutableArray alloc]init];
    shopidarray = [[NSMutableArray alloc]init];
	// Do any additional setup after loading the view.

    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    shopid = shopobj.shopID;
    isclick = NO;
    isnoobj = NO;
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[PMGlobal getInstance]getretimage];
    [b setImage:img forState:UIControlStateNormal];
    b.frame = CGRectMake(10, 10, img.size.width, img.size.height);
    [b addTarget:self action:@selector(ret) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:b];
    self.navigationItem.leftBarButtonItem = left;
   // [self.navigationController.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationbar1.png"] forBarMetrics:UIBarMetricsDefault];
    
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshorder:) name:@"refreshorder" object:nil];
    searchproduct = [[NSMutableArray alloc]init];
    
    
#ifdef DHH_iOS
    img = [[UIHelper getInstance] getBundleImage:@"iphone_tint1.png"];
    filtertint = [[UIImageView alloc]initWithImage:img];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        filtertint.frame = CGRectMake(0, 64, img.size.width, img.size.height);
    }
    else
    {
        filtertint.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    }
    filtertint.userInteractionEnabled = YES;
    [self.view addSubview:filtertint];
    
    tint = [[UIImageView alloc]initWithImage:img];
    tint.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    tint.top = filtertint.bottom;
    tint.userInteractionEnabled = YES;
    [self.view addSubview:tint];
    
    if (numtag ==1) {
        UIImage *img = [[UIHelper getInstance] getBundleImage:@"push.png"];
        UISegmentedControl *segment=[[UISegmentedControl alloc]initWithFrame:CGRectMake(300, 0, img.size.width*3, img.size.height)];
        segment.center = CGPointMake(tint.width/2, tint.height/2);
        [segment insertSegmentWithTitle:@"已上传订单" atIndex:0 animated:YES];
        [segment insertSegmentWithTitle:@"未上传订单" atIndex:1 animated:YES];
        [segment insertSegmentWithTitle:@"取消款" atIndex:2 animated:YES];
        // [segment setImage:[[UIHelper getInstance] getBundleImage:@"push.png"] forSegmentAtIndex:0];
        // [segment setImage:[[UIHelper getInstance] getBundleImage:@"unpush.png"] forSegmentAtIndex:1];
        segment.segmentedControlStyle=UISegmentedControlStyleBar;
        segment.SelectedSegmentIndex=0;
        segment.momentary=NO;
        segment.multipleTouchEnabled=YES;
        [segment addTarget:self action:@selector(setbutton:) forControlEvents:UIControlEventValueChanged];
        [tint addSubview:segment];
        
        submit = 1;
        
        ShopObject *shopobj=[[DataManager sharedManager]getCurrentShop];
        unsubproducts = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
        unsubcount = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
        NSString *str = [NSString stringWithFormat:@"%d",unsubproducts.count];
        unsubcount.font = [UIFont systemFontOfSize:14];
        if (unsubproducts.count==0) {
            unsubcount.hidden = YES;
        }
        else
        {
            unsubcount.hidden = NO;
            unsubcount.text = str;
        }
        unsubcount.adjustsFontSizeToFitWidth = YES;
        unsubcount.backgroundColor = [UIColor colorWithRed:143/255.0 green:90/255.0 blue:54/255.0 alpha:1];
        unsubcount.layer.cornerRadius = 10;
        unsubcount.layer.borderColor = [UIColor whiteColor].CGColor;
        unsubcount.layer.borderWidth = 3;
        unsubcount.textAlignment = UITextAlignmentCenter;
        unsubcount.textColor = [UIColor whiteColor];
        unsubcount.right = 200;
        unsubcount.top = 0;
        [tint addSubview:unsubcount];
    }
    else
    {
        collectsuit = [UIButton buttonWithType:UIButtonTypeCustom];
        collectsuit.frame = CGRectMake(55, 10, 80, 25);
        [collectsuit setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"anniu.png"] forState:UIControlStateNormal];
        [collectsuit setTitle:@"配装收藏" forState:UIControlStateNormal];
        [collectsuit addTarget:self action:@selector(collectsuit:) forControlEvents:UIControlEventTouchUpInside];
        [tint addSubview:collectsuit];
    }
//    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 23)];
//    search.backgroundColor = [UIColor clearColor];
//    search.center = CGPointMake(self.view.width/2, [[UIHelper getInstance] getBundleImage:@"iphone_tint1.png"].size.height/2);
//    search.delegate = self;
//    [tint addSubview:search];
//    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
//    [self.view addGestureRecognizer:tap];
//    self.view.userInteractionEnabled = YES;


    num = 20;
#else
//    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 100, 23)];
//    search.backgroundColor = [UIColor clearColor];
//    search.center = CGPointMake(930, self.navigationController.navigationBar.height/2+2);
//    search.delegate = self;
//    [self.navigationController.navigationBar addSubview:search];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
//    [self.view addGestureRecognizer:tap];
    self.view.userInteractionEnabled = YES;

    num = 20;
    
    UIImage *tintImage = [[UIHelper getInstance] getBundleImage:@"detail_tint.png"];
    tintImage = [tintImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16)];
    
    tint = [[UIImageView alloc]initWithImage:tintImage];
    tint.width = 1024;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        tint.top = 64;
    }
    tint.userInteractionEnabled = YES;
    [self.view addSubview:tint];
    
    if (numtag ==1) {
        UIImage *img = [[UIHelper getInstance] getBundleImage:@"push.png"];
        UISegmentedControl *segment=[[UISegmentedControl alloc]initWithFrame:CGRectMake(300, 0, img.size.width*3, img.size.height)];
        segment.center = CGPointMake(tint.width/2, tint.height/2);
        [segment insertSegmentWithTitle:@"已上传订单" atIndex:0 animated:YES];
        [segment insertSegmentWithTitle:@"未上传订单" atIndex:1 animated:YES];
        [segment insertSegmentWithTitle:@"取消款" atIndex:2 animated:YES];
        // [segment setImage:[[UIHelper getInstance] getBundleImage:@"push.png"] forSegmentAtIndex:0];
        // [segment setImage:[[UIHelper getInstance] getBundleImage:@"unpush.png"] forSegmentAtIndex:1];
        segment.segmentedControlStyle=UISegmentedControlStyleBar;
        segment.SelectedSegmentIndex=0;
        segment.momentary=NO;
        segment.multipleTouchEnabled=YES;
        [segment addTarget:self action:@selector(setbutton:) forControlEvents:UIControlEventValueChanged];
        [tint addSubview:segment];
        
        submit = 1;
        
        unsubcount = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
        unsubcount.font = [UIFont systemFontOfSize:14];

        unsubcount.adjustsFontSizeToFitWidth = YES;
        unsubcount.backgroundColor = [UIColor colorWithRed:143/255.0 green:90/255.0 blue:54/255.0 alpha:1];
        unsubcount.layer.cornerRadius = 10;
        unsubcount.layer.borderColor = [UIColor whiteColor].CGColor;
        unsubcount.layer.borderWidth = 3;
        unsubcount.textAlignment = UITextAlignmentCenter;
        unsubcount.textColor = [UIColor whiteColor];
        unsubcount.right = 550;
        unsubcount.top = 0;
        [tint addSubview:unsubcount];
        
        [self ordernumrefresh1:nil];
    }
    else
    {
        collectsuit = [UIButton buttonWithType:UIButtonTypeCustom];
        collectsuit.frame = CGRectMake(55, 10, 80, 40);
        collectsuit.center = CGPointMake(900, tint.height/2);
        [collectsuit setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"anniu.png"] forState:UIControlStateNormal];
        [collectsuit setTitle:@"配装收藏" forState:UIControlStateNormal];
        [collectsuit addTarget:self action:@selector(collectsuit:) forControlEvents:UIControlEventTouchUpInside];
        [tint addSubview:collectsuit];
    }
    
#endif
    
#ifdef DHH_iOS
    filterBtns_ = [NSMutableArray array];
    filterscroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, filtertint.width, filtertint.height)];
    filterscroll.delegate = self;
    [filtertint addSubview:filterscroll];
    
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        
        UIButton *b = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 120, filtertint.height)];
        [b setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
        [filterscroll addSubview:b];
        [b setBackgroundColor:[UIColor clearColor]];
        [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        b.titleLabel.adjustsFontSizeToFitWidth=YES;
        b.titleLabel.font = [UIFont systemFontOfSize:14];
        //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
        b.left = (b.width+10)*i;
        [b addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
        [filterBtns_ addObject:b];
        b.tag = [[keyCategories_ objectAtIndex:i] intValue];
       // b.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
        
        KeyObject* firstkey = [[[DataManager sharedManager]getKeyObjects:(i+1)]objectAtIndex:0];
        [b setTitle:firstkey.keyName forState:UIControlStateNormal];
        [KeyFilter addObject:firstkey];
        CGSize s = [firstkey.keyName sizeWithFont:b.titleLabel.font];
        if (s.width>98) {
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(98-56)/2, 0, 0);
        }
        else
        {
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(s.width-56)/2, 0, 0);
        }
        filterscroll.contentSize = CGSizeMake(b.right, filtertint.height);
    }
    //初始化菜单
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        
        [self updateKeyButton:i+1];
    }
    
    UIImage *bgImage = [[UIHelper getInstance] getBundleImage:@"iphone_back.png"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:bgImage];
    [self getRefreshProduct];
#else
        filterBtns_ = [NSMutableArray array];
        for ( int i = 0; i < keyCategories_.count; i++ ) {
            
            UIButton *b = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 120, tint.height)];
            [b setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
            [tint addSubview:b];
            [b setBackgroundColor:[UIColor clearColor]];
            [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            b.titleLabel.font = [UIFont systemFontOfSize:14];
            b.titleLabel.adjustsFontSizeToFitWidth=YES;
            //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
            //当订单统计时，然条件分布在两边
            if (numtag==1) {
                if (i<3) {
                    b.left = (b.width+10)*i;
                }
                else{
                    b.left = (b.width+10)*i+235;
                }
            }
            else
            {
                b.left = (b.width+10)*i;
            }
            
            [b addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
            [filterBtns_ addObject:b];
            b.tag = [[keyCategories_ objectAtIndex:i] intValue];
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
            
            KeyObject* firstkey = [[[DataManager sharedManager]getKeyObjects:(i+1)]objectAtIndex:0];
            [b setTitle:firstkey.keyName forState:UIControlStateNormal];
            CGSize s = [firstkey.keyName sizeWithFont:b.titleLabel.font];
            if (s.width>98) {
                b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(98-56)/2, 0, 0);
            }
            else
            {
                b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(s.width-56)/2, 0, 0);
            }

            [KeyFilter addObject:firstkey];
            
        }
        //初始化菜单
        for ( int i = 0; i < keyCategories_.count; i++ ) {
            
            [self updateKeyButton:i+1];
        }
        

        [self getRefreshProduct];
    
    //暂时去掉多店铺过滤
//    totalshop = [[UIHelper getInstance] createButtonByFrame:CGRectMake(820, 0, 100, tint.height)];
//    [totalshop setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
//    [tint addSubview:totalshop];
//    [totalshop setBackgroundColor:[UIColor clearColor]];
//    [totalshop setTitle:@"全部店铺" forState:UIControlStateNormal];
//    
//    [totalshop setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//    totalshop.titleLabel.font = [UIFont systemFontOfSize:14];
//    //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
//    // b.left = (b.width+30)*i;
//    [totalshop addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
//    totalshop.tag = 102;
//    totalshop.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
    
    UIImage *bgImage = [[UIHelper getInstance] getBundleImage:@"suit_bg.jpg"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:bgImage];
#endif

}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidDisappear:(BOOL)animated
{
}

-(void)submitbyself{
   // if ([[AppManager sharedManager]getSubmitStatus]) {
   //     return;
   // }
    
    [WaitTooles showHUD:@"提交订单"];
    [[PMGlobal getInstance] isWifiOn:^(id res){
        
        if (res) {
            
            [[AppManager sharedManager] pauseAutoUpdateSession];
            [[AppManager sharedManager] pauseAutoSubmitSession];
            
            [[AppManager sharedManager]setSubmitStatus:YES];
            [[AppManager sharedManager] forceSubmitAllOrder:^(id res){
                if (res) {
                    [WaitTooles removeHUD];
                }
                
                [[AppManager sharedManager] resumeAutoUpdateSession];
                [[AppManager sharedManager] resetAutoSubmitSession];
                
            }];
            
        }
        else
        {
            [WaitTooles removeHUD];
            showMessage(@"网络连接失败");
        }
    }];
}

- (void)updateKeyButton:(int)selectedCategory{
    
    KeyObject* key = [KeyFilter objectAtIndex:selectedCategory-1];
    
    UIButton* btn = (UIButton*)[filterBtns_ objectAtIndex:key.categoryCode-1];
    
    [btn setTitle:key.keyName forState:UIControlStateNormal];
    
    CGSize s = [key.keyName sizeWithFont:btn.titleLabel.font];
    if (s.width>98) {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(98-56)/2, 0, 0);
    }
    else
    {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(s.width-56)/2, 0, 0);
    }

    
    //层层往下找，是否有连动的子级菜单
    NSArray*child = [[DataManager sharedManager]getChildrenKeyObjects:key.keyID];
    
    if (child.count>0) {
        //取第一个值作为过滤条件
        KeyObject *firstchild = [child objectAtIndex:0];
        
        [KeyFilter replaceObjectAtIndex:firstchild.categoryCode-1 withObject:firstchild];
        
        UIButton* btn = (UIButton*)[filterBtns_ objectAtIndex:firstchild.categoryCode-1];
        
        [btn setTitle:firstchild.keyName forState:UIControlStateNormal];
        
        //如果能找到子集菜单则递归调用子集
        [self updateKeyButton:firstchild.categoryCode];
    }
    
}

//统一的刷新方法
-(void)getRefreshProduct{
    if (numtag ==1) {
        if (submit == 2) {
            product = [[DataManager sharedManager] getCanceledOrderProducts:KeyFilter  Shopid:shopid];
        }
        else
        {
            product = [[DataManager sharedManager] getOrderedProducts:KeyFilter  Shopid:shopid Submit:submit];
        }
        [self setOrdercount:product.count];
    }
    else
    {
        if (isclick == NO) {
            product = [[DataManager sharedManager] getFavoriteProducts:KeyFilter  Shopid:shopid];
        }
        else
        {
            product = [[DataManager sharedManager] getsuitFavoriteProducts:KeyFilter  Shopid:shopid];
        }
    }
    
    
    [self newfresh:product];
}

-(void)newfresh:(NSArray*)products
{
    isnoobj = NO;
    if (isclick==NO) {
#ifdef DHH_iOS
    page = 0;
    num = 20;
    
    [scroll removeFromSuperview];
    int maxCol = 2;
    float xOffset = 10;
    float yOffset = 20;
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"detail_tint.png"];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+img.size.height, 320,self.view.height-tint.bottom-10)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+img.size.height, 320,self.view.height-tint.bottom-10-44)];
    }
    scroll.backgroundColor = [UIColor clearColor];
    scroll.top = tint.bottom+10;
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    float height = 0;
    for (int i = 0; i < num&& i<products.count; i++) {
        
        ProductObject *obj = [products objectAtIndex:i];
        
        //标志是否取消款页面来修改图片上的颜色
        int cancelfalg = 0;
        
        if (submit==2) {
            cancelfalg =2;
        }
        else{
            cancelfalg =1;
        }
        
        
        ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:cancelfalg];
        
        v.tag = 100+i;
        NSString *url = [NSString stringWithFormat:@"_%@",obj.pURL];
        NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
        UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
        if (img==nil) {
            v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
        }
        else
        {
            v.imageview.image = img;
        }
        
        [scroll addSubview:v];
        
        int row = i / maxCol;
        int col = i % maxCol;
        
        v.left = xOffset + col * (v.width + 10);
        v.top = yOffset + row * (v.height + 10);
        
        height = v.bottom+10;
    }
    
    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 320, 0)];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
    [self setRefreshView];
#else
    page = 0;
    num = 20;
    
    [scroll removeFromSuperview];
    int maxCol = 5;
    float xOffset = 50;
    float yOffset = 30;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-64)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-54)];
    }
    scroll.backgroundColor = [UIColor clearColor];
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    float height = 0;
    for (int i = 0; i < num&& i<products.count; i++) {
            
        ProductObject *obj = [products objectAtIndex:i];
        
        //标志是否取消款页面来修改图片上的颜色
        int cancelfalg = 0;
        
        if (submit==2) {
            cancelfalg =2;
        }
        else{
            cancelfalg =1;
        }
        
        
        ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:cancelfalg];
        
        v.tag = 100+i;
        NSString *url = [NSString stringWithFormat:@"_%@",obj.pURL];
        NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
        UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
        
        if ([[PMGlobal getInstance]isImageEnable]) {
            if (img) {
                v.imageview.image = img;
            }else{
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
            }
        }else{
            v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
        }
        
        [scroll addSubview:v];
        
        int row = i / maxCol;
        int col = i % maxCol;
        
        v.left = xOffset + col * (v.width + 20);
        v.top = yOffset + row * (v.height + 20);
        
        height = v.bottom;
    }
    
    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 1024, 0)];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
    [self setRefreshView];
#endif
    }
    else
    {
#ifdef DHH_iOS
        page = 0;
        num = 20;
        
        [scroll removeFromSuperview];
        int maxCol = 2;
        float xOffset = 10;
        float yOffset = 20;
        UIImage *img = [[UIHelper getInstance] getBundleImage:@"detail_tint.png"];
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
        {
            scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+img.size.height, 320,self.view.height-tint.bottom-10)];
        }
        else
        {
            scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+img.size.height, 320,self.view.height-tint.bottom-10-44)];
        }
        scroll.backgroundColor = [UIColor clearColor];
        scroll.top = tint.bottom+10;
        scroll.delegate = self;
        [self.view addSubview:scroll];
        
        float height = 0;
        for (int i = 0; i < num&& i<products.count; i++) {
            
            SuitObject *obj = [products objectAtIndex:i];
            
            //标志是否取消款页面来修改图片上的颜色
            int cancelfalg = 0;
            
            if (submit==2) {
                cancelfalg =2;
            }
            else{
                cancelfalg =1;
            }
            
            
            SuitThumbView *v = [[SuitThumbView alloc] initWithProduct:obj tag:cancelfalg];
            
            v.tag = 100+i;
            NSString *url = [NSString stringWithFormat:@"_%@",obj.pic_path];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if (img==nil) {
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
            }
            else
            {
                v.imageview.image = img;
            }
            
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 10);
            v.top = yOffset + row * (v.height + 10);
            
            height = v.bottom+10;
        }
        
        scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        
        refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 320, 0)];
        refreshView.delegate = self;
        refreshView.top = scroll.bottom;
        
        [scroll addSubview:refreshView];
        [self setRefreshView];
#else
        page = 0;
        num = 20;
        
        [scroll removeFromSuperview];
        int maxCol = 5;
        float xOffset = 50;
        float yOffset = 30;
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
        {
            scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-64)];
        }
        else
        {
            scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-54)];
        }
        scroll.backgroundColor = [UIColor clearColor];
        scroll.delegate = self;
        [self.view addSubview:scroll];
        
        float height = 0;
        for (int i = 0; i < num&& i<products.count; i++) {
            
            SuitObject *obj = [products objectAtIndex:i];
            
            //标志是否取消款页面来修改图片上的颜色
            int cancelfalg = 0;
            
            if (submit==2) {
                cancelfalg =2;
            }
            else{
                cancelfalg =1;
            }
            
            
            SuitThumbView *v = [[SuitThumbView alloc] initWithProduct:obj tag:cancelfalg type:SuitView_obj];
            
            v.tag = 100+i;
            NSString *url = [NSString stringWithFormat:@"_%@",obj.pic_path];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if ([[PMGlobal getInstance]isImageEnable]) {
                if (img) {
                    v.imageview.image = img;
                }else{
                    v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
                }
            }else{
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
            }
            
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 20);
            v.top = yOffset + row * (v.height + 20);
            
            height = v.bottom;
        }
        
        scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        
        refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 1024, 0)];
        refreshView.delegate = self;
        refreshView.top = scroll.bottom;
        
        [scroll addSubview:refreshView];
        [self setRefreshView];
#endif
    }
    [self.view bringSubviewToFront:backview];
}


-(void)ret
{
    //[[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];
    refreshView.delegate = nil;
    UIImage *img = [[PMGlobal getInstance]getnavigationbarimage];
    [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    [search removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark 进入细节页面
//- (void)toDetail:(NSNotification *)notification{
//    UIImage *img = [[PMGlobal getInstance]getnavigationbarimage];
//    [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
//    search.hidden = YES;
//    ProductObject *obj = (ProductObject *)notification.object;
//    ProductDetailViewControllerEx *detail = [[ProductDetailViewControllerEx alloc] initWithProduct:obj];
//    detail.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:detail animated:YES];
//}

-(void)next
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    next.transform = CGAffineTransformRotate(next.transform, -90 * M_PI / 180);
    [UIView commitAnimations];
}
-(void)next1
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    next1.transform = CGAffineTransformRotate(next.transform, -90 * M_PI / 180);
    [UIView commitAnimations];
}

//请求数据
-(void)reloadData
{
    reloading = YES;
    //新建一个线程来加载数据
    [NSThread detachNewThreadSelector:@selector(requestData)
                             toTarget:self
                           withObject:nil];
}

-(void)requestData
{
    sleep(1);
    //在主线程中刷新UI
    [self performSelectorOnMainThread:@selector(reloadUI)
                           withObject:nil
                        waitUntilDone:NO];
}

-(void)reload
{
    if (isclick==NO) {
#ifdef DHH_iOS
    // [scroll removeFromSuperview];
    [refreshView removeFromSuperview];
    int maxCol = 2;
    float xOffset = 10;
    float yOffset = 20;
    num+=20;
    // scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+[[UIHelper getInstance] getBundleImage:@"detail_tint.png"].size.height, 1024,748-44)];
    // scroll.backgroundColor = [UIColor clearColor];
    // scroll.delegate = self;
    // [self.view addSubview:scroll];
    
    float height = 0;
        page+=1;
        for (int i = num-20; i < num && i<product.count; i++) {
            ProductObject *obj = [product objectAtIndex:i-20*page];
            int cancelfalg = 0;
            
            if (submit==2) {
                cancelfalg =2;
            }
            else{
                cancelfalg =1;
            }
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:cancelfalg];
            
            v.tag = 100+i;
            NSString *url = [NSString stringWithFormat:@"_%@",obj.pURL];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if (img==nil) {
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
            }
            else
            {
                v.imageview.image = img;
            }

            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 10);
            v.top = yOffset + row * (v.height + 10);
            
            height = v.bottom+10;
        }
    
    if (num<product.count) {
        scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    }
    else
    {
        showMessage(@"没数据了");
        if (isnoobj == NO) {
            if (height!=0) {
                scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
            }
            isnoobj = YES;
        }
        if (scroll.contentSize.height<350) {
            scroll.contentOffset = CGPointMake(0, 0);
        }
        else
        {
            scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-350);
        }

    }
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
#else
    // [scroll removeFromSuperview];
    [refreshView removeFromSuperview];
    int maxCol = 5;
    float xOffset = 50;
    float yOffset = 30;
    num+=20;
    // scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+[[UIHelper getInstance] getBundleImage:@"detail_tint.png"].size.height, 1024,748-44)];
    // scroll.backgroundColor = [UIColor clearColor];
    // scroll.delegate = self;
    // [self.view addSubview:scroll];
    
    float height = 0;
        page+=1;
        for (int i = num-20; i < num && i<product.count; i++) {

            ProductObject *obj = [product objectAtIndex:i];
            //标志是否取消款页面来修改图片上的颜色
            int cancelfalg = 0;
            
            if (submit==2) {
                cancelfalg =2;
            }
            else{
                cancelfalg =1;
            }
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:cancelfalg];
            
            v.tag = 100+i;
            NSString *url = [NSString stringWithFormat:@"_%@",obj.pURL];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if ([[PMGlobal getInstance]isImageEnable]) {
                if (img) {
                    v.imageview.image = img;
                }else{
                    v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
                }
            }else{
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
            }
        
            [scroll addSubview:v];
        
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 20);
            v.top = yOffset + row * (v.height + 20);
            
            height = v.bottom;
        }
    if (num<product.count) {
        scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    }
    else
    {
        showMessage(@"没数据了");
        if (isnoobj == NO) {
            if (height!=0) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
            }
            isnoobj = YES;
        }
        if (scroll.contentSize.height<710) {
            scroll.contentOffset = CGPointMake(0, 0);
        }
        else
        {
        scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-710);
        }
    }
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
#endif
    }
    else
    {
#ifdef DHH_iOS
        // [scroll removeFromSuperview];
        [refreshView removeFromSuperview];
        int maxCol = 2;
        float xOffset = 10;
        float yOffset = 20;
        num+=20;
        // scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+[[UIHelper getInstance] getBundleImage:@"detail_tint.png"].size.height, 1024,748-44)];
        // scroll.backgroundColor = [UIColor clearColor];
        // scroll.delegate = self;
        // [self.view addSubview:scroll];
        
        float height = 0;
        page+=1;
        for (int i = num-20; i < num && i<product.count; i++) {
            SuitObject *obj = [product objectAtIndex:i];
            //标志是否取消款页面来修改图片上的颜色
            int cancelfalg = 0;
            
            if (submit==2) {
                cancelfalg =2;
            }
            else{
                cancelfalg =1;
            }
            SuitThumbView *v = [[SuitThumbView alloc] initWithProduct:obj tag:cancelfalg];
            
            v.tag = 100+i;
            NSString *url = [NSString stringWithFormat:@"_%@",obj.pic_path];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if (img==nil) {
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
            }
            else
            {
                v.imageview.image = img;
            }
            
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 10);
            v.top = yOffset + row * (v.height + 10);
            
            height = v.bottom+10;
        }
        
        if (num<product.count) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        }
        else
        {
            showMessage(@"没数据了");
            if (isnoobj == NO) {
                if (height!=0) {
                    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
                }
                isnoobj = YES;
            }
            if (scroll.contentSize.height<350) {
                scroll.contentOffset = CGPointMake(0, 0);
            }
            else
            {
                scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-350);
            }

        }
        
        refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
        refreshView.delegate = self;
        refreshView.top = scroll.bottom;
        
        [scroll addSubview:refreshView];
#else
        // [scroll removeFromSuperview];
        [refreshView removeFromSuperview];
        int maxCol = 5;
        float xOffset = 50;
        float yOffset = 30;
        num+=20;
        // scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+[[UIHelper getInstance] getBundleImage:@"detail_tint.png"].size.height, 1024,748-44)];
        // scroll.backgroundColor = [UIColor clearColor];
        // scroll.delegate = self;
        // [self.view addSubview:scroll];
        
        float height = 0;
        page+=1;
        for (int i = num-20; i < num && i<product.count; i++) {
            
            SuitObject *obj = [product objectAtIndex:i];
            //标志是否取消款页面来修改图片上的颜色
            int cancelfalg = 0;
            
            if (submit==2) {
                cancelfalg =2;
            }
            else{
                cancelfalg =1;
            }
            SuitThumbView *v = [[SuitThumbView alloc] initWithProduct:obj tag:cancelfalg type:SuitView_obj];
            
            v.tag = 100+i;
            NSString *url = [NSString stringWithFormat:@"_%@",obj.pic_path];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            UIImage *img = [imageCache_ imageForKey:url url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if ([[PMGlobal getInstance]isImageEnable]) {
                if (img) {
                    v.imageview.image = img;
                }else{
                    v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
                }
            }else{
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
            }
            
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 20);
            v.top = yOffset + row * (v.height + 20);
            
            height = v.bottom;
        }
        if (num<product.count) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        }
        else
        {
            showMessage(@"没数据了");
            if (isnoobj == NO) {
                if (height!=0) {
                    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
                }
                isnoobj = YES;
            }
            if (scroll.contentSize.height<710) {
                scroll.contentOffset = CGPointMake(0, 0);
            }
            else
            {
                scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-710);
            }

        }
        refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
        refreshView.delegate = self;
        refreshView.top = scroll.bottom;
        
        [scroll addSubview:refreshView];
#endif
    }
}
-(void)reloadUI
{
	reloading = NO;
    
    //停止下拉的动作,恢复表格的偏移
	[refreshView egoRefreshScrollViewDataSourceDidFinishedLoading:scroll];
    //更新界面
    [self reload];
    
    [self setRefreshViewFrame];
}
-(void)setRefreshView
{
#ifdef DHH_iOS
    //如果contentsize的高度比表的高度小，那么就需要把刷新视图放在表的bounds的下面
    int height = MAX(scroll.bounds.size.height, scroll.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, 320, scroll.bounds.size.height);
#else
    int height = MAX(scroll.bounds.size.height, scroll.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, 1024, scroll.bounds.size.height);
#endif
}

-(void)setRefreshViewFrame
{
    //如果contentsize的高度比表的高度小，那么就需要把刷新视图放在表的bounds的下面
    int height = MAX(scroll.bounds.size.height, scroll.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, self.view.frame.size.width, scroll.bounds.size.height);
}
-(void)tap
{
    if(tint.userInteractionEnabled == NO)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.1];
        next.transform = CGAffineTransformRotate(next.transform, 90 * M_PI / 180);
        [UIView commitAnimations];
        
        tint.userInteractionEnabled = YES;
    }
}

#pragma mark - EGORefreshTableFooterDelegate
//出发下拉刷新动作，开始拉取数据
- (void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView*)view
{
    [self reloadData];
}
//返回当前刷新状态：是否在刷新
- (BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView*)view
{
    return reloading;
}
//返回刷新时间
-(NSDate *)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView *)view
{
    return [NSDate date];
}

#pragma mark - UIScrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    distance = filterscroll.contentOffset.x;
   // if (isclick==NO) {
        [refreshView egoRefreshScrollViewDidScroll:scrollView];
   // }
    
}
//松开后判断表格是否在刷新，若在刷新则表格位置偏移，且状态说明文字变化为loading...
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
   // if (isclick==NO) {
        [refreshView egoRefreshScrollViewDidEndDragging:scrollView];
   // }
   // else
   // {
   //     if (decelerate) {
   //         [self updatePage:scrollView];
   //     }
   // }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    /*
    if (isclick==NO) {
    }
    else
    {
    [self updatePage:scrollView];
    }
     */
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 过滤条件按钮点击事件
- (void)keyClicked:(UIButton *)sender{
    if (isclick==NO) {
        NSMutableArray *items = [NSMutableArray array];
        int tag = 0;
        
        if(sender.tag == 102){
            
            ShopObject* allshop = [[ShopObject alloc]init];
            allshop.shopName = @"全部店铺";
            [items addObject:allshop];
            for (int i = 0;i<shop.count;i++) {
                ShopObject *shopobj = [shop objectAtIndex:i];
                [items addObject:shopobj];
            }
            
            tag = sender.tag;
        }
        else{
            
            tag = sender.tag;
            
            //先获取点击的按钮的当前过滤条件，以此得到父ID
            KeyObject* key = [KeyFilter objectAtIndex:tag-1];
            
            //若父ID为0则表示无上级目录，直接取这个过滤条件的所有项
            if (key.parentCode==0) {
                items = [[DataManager sharedManager]getKeyObjects:tag];
            }
            /*
            if (key.parentCode==0) {
                items = [[DataManager sharedManager]getKeyObjects:tag];
            }
             */
            else{
                //有上次则根据上次获取该父亲下的所有子目录
                items = [[DataManager sharedManager]getChildrenKeyObjects:key.parentCode];
            }
            //为了传给参数控件进行识别而进行修改
            tag = tag+200;
            
        }
        //   [[NSNotificationCenter defaultCenter]postNotificationName:@"pass" object:items];
        if (numtag==2) {
            tag = tag+100;
        }
        
        controller = [[DemoTableController alloc] initWithStyle:UITableViewStylePlain items:items tag:tag];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
        popover.distance = distance;
        //popover.arrowDirection = FPPopoverArrowDirectionAny;
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(300, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        
        //sender is the UIButton view
        sender.left -=distance;
        [popover presentPopoverFromView:sender];
        sender.left +=distance;
    }
    else
    {
        int category = sender.tag;
        
        //先获取点击的按钮的当前过滤条件，以此得到父ID
        KeyObject* key = [KeyFilter objectAtIndex:category-1];
        
        //若父ID为0则表示无上级目录，直接取这个过滤条件的所有项
        NSMutableArray* arr;
        if (key.parentCode==0) {
            arr = [[DataManager sharedManager]getKeyObjects:category];
        }
        else{
            //有上次则根据上次获取该父亲下的所有子目录
            arr = [[DataManager sharedManager]getChildrenKeyObjects:key.parentCode];
        }
        
        //the controller we want to present as a popover
        shopcontroller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain items:arr tag:sender.tag+300];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:shopcontroller];
        popover.distance = distance;
        //popover.arrowDirection = FPPopoverArrowDirectionAny;
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(300, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        
        //sender is the UIButton view
        sender.left -=distance;
        [popover presentPopoverFromView:sender];
        sender.left +=distance;
    }
}




#pragma mark 
#pragma mark 点击过滤条件更新产品
-(void)index2:(NSNotification *)sender
{
    NSDictionary* dic =  sender.object;
    
    KeyObject* key = [dic objectForKey:@"key"];
    
    [KeyFilter replaceObjectAtIndex:[[dic objectForKey:@"category"]intValue]-201 withObject:key];
    
    int num1 = [[dic objectForKey:@"category"]intValue]-200;
    [self updateKeyButton:num1];
    
    [self getRefreshProduct];
    
    [backview removeFromSuperview];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}

#pragma mark 点击过滤条件更新产品
-(void)index3:(NSNotification *)sender
{
    NSDictionary* dic =  sender.object;
    
    KeyObject* key = [dic objectForKey:@"key"];
    
    [KeyFilter replaceObjectAtIndex:[[dic objectForKey:@"category"]intValue]-301 withObject:key];
    
    int num1 = [[dic objectForKey:@"category"]intValue]-300;
    [self updateKeyButton:num1];
    
    [self getRefreshProduct];
    
    [backview removeFromSuperview];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}

#pragma mark 更换店铺换标题
-(void)statRefreshShop:(NSNotification *)sender
{
    NSDictionary *dic = sender.object;
    [totalshop setTitle:[dic objectForKey:@"title"] forState:UIControlStateNormal];
        
    shopid = [dic objectForKey:@"shopid"];
#ifdef DHH_iOS
//    [self refreshiphone:num1 coatkeys:keys];
    [self getRefreshProduct];
#else
    [self getRefreshProduct];
    
#endif
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}


- (UIButton *)getFilterButtonByCode:(int)code{
    for (UIButton *b in filterBtns_) {
        if (b.tag == code) {
            return b;
        }
    }
    
    return nil;
}

/*
-(void)hidden:(NSNotification *)sender
{
#ifdef DHH_iOS
    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 23)];
    search.backgroundColor = [UIColor clearColor];
    search.center = CGPointMake(self.view.width/2, tint.size.height/2);
    search.delegate = self;
    [tint addSubview:search];
#else
    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 100, 23)];
    search.backgroundColor = [UIColor clearColor];
    search.center = CGPointMake(930, self.navigationController.navigationBar.height/2+2);
    search.delegate = self;
    [self.navigationController.navigationBar addSubview:search];
#endif

}
 */
//-(void)refreshorder:(NSNotification *)sender
//{
//   //[self refresh1];
//}
//-(BOOL)textFieldShouldReturn:(UITextField *)textField
//{
//    [textField resignFirstResponder];
//    [self refresh1];
//    return YES;
//}



-(void)setbutton:(UISegmentedControl *)Seg{
    
    NSInteger Index = Seg.selectedSegmentIndex;
    
    switch (Index) {
         
        //已提交
        case 0:
            
            submit =1;
            
            break;
        //未提交
        case 1:
            submit=0;
            
            break;
        //表示取消款
        case 2:
            submit=2;
            
            break;
        default:
            
            break;
            
    }
    [self getRefreshProduct];
    
}

#ifdef DHH_iOS
#else
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (BOOL)shouldAutorotate{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}
#endif

#pragma mark 给产品框赋予图片
- (void)static_image:(NSNotification *)notification{
    NSDictionary *dict = [notification userInfo];
    UIImage *img = [dict objectForKey:@"image"];
    
    
    if ([[PMGlobal getInstance]isImageEnable]) {
        if (img) {
        }else{
            img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
        }
    }else{
        img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
    }
    
    int tag = [[dict objectForKey:@"tag"] intValue];
    if (isclick==NO) {

        ProductThumbView *v = (ProductThumbView *)[scroll viewWithTag:tag];
        v.imageview.image = img;
    }
    else
    {
        SuitThumbView *v = (SuitThumbView *)[scroll viewWithTag:tag];
        v.imageview.image = img;
    }
}

-(void)copytopaste
{
    if(shop.count<2)
    {
        showMessage(@"其他店铺不存在");
    }
    else
    {
        [backview removeFromSuperview];
        backview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        backview.userInteractionEnabled=YES;
        backview.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        [self.view addSubview:backview];
#ifdef DHH_iOS
        UIImage *img = [[UIHelper getInstance] getBundleImage:@"detail_copyback_iphone.png"];
        copytopaste = [[UIImageView alloc]initWithImage:img];
        copytopaste.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        copytopaste.center = CGPointMake(self.view.width/2, self.view.height/2);
        copytopaste.userInteractionEnabled = YES;
        [backview addSubview:copytopaste];
        
        UIButton *paste = [UIButton buttonWithType:UIButtonTypeCustom];
        img = [[UIHelper getInstance] getBundleImage:@"anniu_iphone.png"];
        [paste setBackgroundImage:img forState:UIControlStateNormal];
        paste.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        paste.center = CGPointMake([[UIHelper getInstance] getBundleImage:@"detail_copyback_iphone.png"].size.width/2-50, 190);
        [paste setTitle:@"粘贴" forState:UIControlStateNormal];
        [paste addTarget:self action:@selector(pasteclick) forControlEvents:UIControlEventTouchUpInside];
        [copytopaste addSubview:paste];
        
        UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancel setBackgroundImage:img forState:UIControlStateNormal];
        cancel.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        cancel.center = CGPointMake([[UIHelper getInstance] getBundleImage:@"detail_copyback_iphone.png"].size.width/2+50, 190);
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        [cancel addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
        [copytopaste addSubview:cancel];
        
        shoparray = [[NSMutableArray alloc]init];
        ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
        for (int i = 0; i<shop.count; i++) {
            ShopObject *copyshop = [shop objectAtIndex:i];
            if(![shopobj.shopName isEqualToString:copyshop.shopName] &&
               [copyshop.bOrder boolValue])
            {
                [shoparray addObject:copyshop];
            }
        }
        UIScrollView *copyscrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 70, 170, 96)];
        img = [[UIHelper getInstance] getBundleImage:@"detail_copyback_iphone.png"];
        copyscrollview.center = CGPointMake(img.size.width/2,img.size.height/2);
        [copytopaste addSubview:copyscrollview];
        for (int i = 0; i<shoparray.count; i++) {
            ShopObject *copyshop = [shoparray objectAtIndex:i];
            
            shopview = [[UIView alloc]initWithFrame:CGRectMake(0, i*24, 170, 24)];
            shopview.layer.borderWidth = 1;
            shopview.layer.borderColor = [UIColor grayColor].CGColor;
            [copyscrollview addSubview:shopview];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(140, 1, 1, 24)];
            line.backgroundColor = [UIColor grayColor];
            [shopview addSubview:line];
            
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 24)];
            label.center = CGPointMake(70, 12);
            label.textAlignment = NSTextAlignmentCenter;
            label.text = copyshop.shopName;
            label.adjustsFontSizeToFitWidth = YES;
            [shopview addSubview:label];
            
            UIButton *select = [UIButton buttonWithType:UIButtonTypeCustom];
            UIImage *img = [UIImage imageNamed:@"detail_shopunselect.png"];
            [select setImage:img forState:UIControlStateNormal];
            select.frame = CGRectMake(0, 0, img.size.width/2, img.size.height/2);
            select.center = CGPointMake(155, 12);
            select.tag = 10 + i;
            [select addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            [shopview addSubview:select];
            copyscrollview.contentSize=CGSizeMake(copyscrollview.width, 24*shoparray.count);
        }
        
#else
        UIImage *img = [[UIHelper getInstance] getBundleImage:@"detail_copyback.png"];
        copytopaste = [[UIImageView alloc]initWithImage:img];
        copytopaste.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        copytopaste.center = CGPointMake(512, 300);
        copytopaste.userInteractionEnabled = YES;
        [backview addSubview:copytopaste];
        
        UIButton *paste = [UIButton buttonWithType:UIButtonTypeCustom];
        [paste setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"anniu.png"] forState:UIControlStateNormal];
        img = [[UIHelper getInstance] getBundleImage:@"detail_paste.png"];
        paste.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        paste.center = CGPointMake([[UIHelper getInstance] getBundleImage:@"detail_copyback.png"].size.width/2-100, 310);
        [paste setTitle:@"粘贴" forState:UIControlStateNormal];
        [paste addTarget:self action:@selector(pasteclick) forControlEvents:UIControlEventTouchUpInside];
        [copytopaste addSubview:paste];
        
        UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancel setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"anniu.png"] forState:UIControlStateNormal];
        img = [[UIHelper getInstance] getBundleImage:@"detail_cancel.png"];
        cancel.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        cancel.center = CGPointMake([[UIHelper getInstance] getBundleImage:@"detail_copyback.png"].size.width/2+100, 310);
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        [cancel addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
        [copytopaste addSubview:cancel];

        
        shoparray = [[NSMutableArray alloc]init];
        ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
        for (int i = 0; i<shop.count; i++) {
            ShopObject *copyshop = [shop objectAtIndex:i];
            if(![shopobj.shopName isEqualToString:copyshop.shopName] &&
               [copyshop.bOrder boolValue])
            {
                [shoparray addObject:copyshop];
            }
        }
        UIScrollView *copyscrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 70, 400, 200)];
        img = [[UIHelper getInstance] getBundleImage:@"detail_copyback.png"];
        copyscrollview.center = CGPointMake(img.size.width/2,img.size.height/2);
        [copytopaste addSubview:copyscrollview];
        for (int i = 0; i<shoparray.count+1; i++) {
            ShopObject *copyshop = nil;
            if (i>0) {
                copyshop = [shoparray objectAtIndex:i-1];
            }
            
            shopview = [[UIView alloc]initWithFrame:CGRectMake(2, i*50, copyscrollview.width-4, 50)];
            shopview.layer.borderWidth = 1;
            shopview.layer.borderColor = [UIColor grayColor].CGColor;
            [copyscrollview addSubview:shopview];
            
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 230, 30)];
            label.center = CGPointMake(150, 25);
            label.left = 10;
            label.textAlignment = NSTextAlignmentCenter;
            if (i>0) {
                label.text = [NSString stringWithFormat:@"%@  %@",copyshop.shopID,copyshop.shopName];
            }else{
                label.text = [NSString stringWithFormat:@"店铺名称"];
            }
            
            label.adjustsFontSizeToFitWidth = YES;
            [shopview addSubview:label];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(label.right+10, 1, 1, 50)];
            line.backgroundColor = [UIColor grayColor];
            [shopview addSubview:line];
            
            UIButton *select = [UIButton buttonWithType:UIButtonTypeCustom];
            UIImage *img = [UIImage imageNamed:@"detail_shopunselect.png"];
            [select setImage:img forState:UIControlStateNormal];
            select.frame = CGRectMake(0, 0, img.size.width+20, img.size.height+20);
            select.center = CGPointMake(318, shopview.height/2);
            select.left = line.right + 10;
            select.tag = 10 + i-1;
            [select addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            [shopview addSubview:select];
            copyscrollview.contentSize=CGSizeMake(copyscrollview.width, 50*(shoparray.count+1));
            if (i==0) {
                //select.hidden = YES;
                [select setImage:nil forState:UIControlStateNormal];
                [select setTitle:@"选中" forState:UIControlStateNormal];
                [select setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                select.userInteractionEnabled = NO;
            }
            
            line = [[UIView alloc]initWithFrame:CGRectMake(select.right+10, 1, 1, 50)];
            line.backgroundColor = [UIColor grayColor];
            [shopview addSubview:line];
            
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
            [shopview addSubview:textField];
            textField.textAlignment = NSTextAlignmentCenter;
            textField.text = @"1";
            textField.tag = 100+i-1;
            textField.delegate = self;
            textField.keyboardType = UIKeyboardTypeNumberPad;
            textField.left = select.right+ 10;
            if (i==0) {
                textField.userInteractionEnabled = NO;
                textField.text = @"复制倍数";
            }
        }
#endif
    }
}
-(void)pasteclick
{
    [shopidarray removeAllObjects];
    // [orders removeAllObjects];
    
    
    [WaitTooles showHUD:@"正在复制订单"];
    dispatch_queue_t paste_queue = dispatch_queue_create("com.yx.pm.paste", NULL);
    dispatch_async(paste_queue, ^(void) {
        UserObject *user=[[DataManager sharedManager]getUserObject];
        for (int i = 0; i<shoparray.count; i++) {
            UIButton *btn = (UIButton *)[copytopaste viewWithTag:10+i];
            if (btn.imageView.image == [UIImage imageNamed:@"detail_shopunselect.png"]) {
                [shopidarray addObject:@"0"];
            }
            else {
                [shopidarray addObject:@"1"];
            }
        }
        if (shopidarray.count==0) {
            return;
        }
        for (int i = 0; i<shopidarray.count; i++) {
            if ([[shopidarray objectAtIndex:i] isEqualToString:@"1"]) {
                ShopObject *shopobj = [shoparray objectAtIndex:i];
                ShopObject *currentshop = [[DataManager sharedManager]getCurrentShop];
                UITextField *f = (UITextField *)[copytopaste viewWithTag:100+i];
                int t = [f.text intValue];
                if (t==0) {
                    t=1;
                }
                [[DataManager sharedManager]Copyorder:user.userCode
                                                 code:nil
                                           FromShopid:currentshop.shopID
                                             ToShopid:shopobj.shopID
                                             withTime:t];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [WaitTooles removeHUD];
            [backview removeFromSuperview];
            backview = nil;
        });

    });

}
-(void)cancelclick
{
    [backview removeFromSuperview];
}
-(void)click:(UIButton *)sender
{
    ShopObject *copyshop = [shoparray objectAtIndex:sender.tag-10];
    UIButton *btn = (UIButton *)[copytopaste viewWithTag:sender.tag];
    if (copyshop.bCheck) {
        showMessage(@"该店铺已经审核，不能提交订单");
        return;
    }
#ifdef DHH_iOS
    if(btn.imageView.image == [UIImage imageNamed:@"detail_shopunselect.png"])
    {
        NSString *str = [NSString stringWithFormat:@"%@",copyshop.bOrder];
        if ([str isEqualToString:@"0"]) {
            showMessage(@"该店铺没有提交订单的权限");
            return;
        }
        UIImage *img =[UIImage imageNamed:@"detail_shopselect.png"];
        [btn setImage:img forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, img.size.width/2, img.size.height/2);
        btn.center = CGPointMake(157, 11);
        
    }
    else
    {
        UIImage *img = [UIImage imageNamed:@"detail_shopunselect.png"];
        [btn setImage:img forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, img.size.width/2, img.size.height/2);
        btn.center = CGPointMake(155, 12);
    }
#else
    if(btn.imageView.image == [UIImage imageNamed:@"detail_shopunselect.png"])
    {
        NSString *str = [NSString stringWithFormat:@"%@",copyshop.bOrder];
        if ([str isEqualToString:@"0"]) {
            showMessage(@"该店铺没有提交订单的权限");
            return;
        }
        UIImage *img = [UIImage imageNamed:@"detail_shopselect.png"];
        [btn setImage:img forState:UIControlStateNormal];
//        btn.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//        btn.center = CGPointMake(322, 22);
        
    }
    else
    {
        UIImage *img = [UIImage imageNamed:@"detail_shopunselect.png"];;
        [btn setImage:img forState:UIControlStateNormal];
//        btn.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//        btn.center = CGPointMake(318, 25);
    }
#endif
}
-(void)collectsuit:(UIButton *)sender
{
    [scroll removeFromSuperview];
    if (isclick==NO) {
        [collectsuit setTitle:@"产品收藏" forState:UIControlStateNormal];
        product = [[DataManager sharedManager] getsuitFavoriteProducts:KeyFilter  Shopid:shopid];
        /*
#ifdef DHH_iOS
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
        {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20, tint.bottom+12, 280, self.view.height-70-64)];
        }
        else
        {
            scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20, tint.bottom+12, 280, self.view.height-70)];
        }
        [self.view addSubview:scroll];
        scroll.backgroundColor = [UIColor clearColor];
        scroll.centerX = 160;
        scroll.top = tint.bottom;
        scroll.showsVerticalScrollIndicator = NO;
        scroll.showsHorizontalScrollIndicator = NO;
        scroll.bounces = NO;
        scroll.clipsToBounds = NO;
        scroll.delegate = self;
        [self updatePage:scroll];
        //  float cWidth = 0;
        
        scroll.contentSize = CGSizeMake(scroll.width * product.count, scroll.height);
        scroll.pagingEnabled = YES;
#else
        float offset = 45;
        UIImage *suitBG = [[UIHelper getInstance] getBundleImage:@"suitView_bg.png"];
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(offset, 0, 1024-offset*2, suitBG.size.height)];
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
        {
             scroll.center = CGPointMake(1024/2, (748+64)/2);
        }
        else
        {
             scroll.center = CGPointMake(1024/2, 748/2);
        }
        [self.view addSubview:scroll];
        scroll.showsHorizontalScrollIndicator = NO;
        scroll.backgroundColor = [UIColor clearColor];
        scroll.clipsToBounds = NO;
        scroll.delegate = self;
        
        //    float cWidth = 0;
        
        //    suitView_ = [NSMutableArray array];
        //    for (int i = 0; i < suits_.count; i++) {
        //        SuitObject *obj = [suits_ objectAtIndex:i];
        //        SuitView *s = [[SuitView alloc] initWithSuitObject:obj];
        //
        //        [suitView_ addObject:s];
        //
        //        [scroll addSubview:s];
        //        s.center = CGPointMake(scroll.width/2 + scroll.width * i, scroll.height/2);
        //        cWidth = s.right;
        //    }
        
        [self updatePage:scroll];
        
        scroll.contentSize = CGSizeMake(scroll.width * product.count, scroll.height);
        scroll.pagingEnabled = YES;
#endif
        [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
         */
        isclick = YES;
        [self newfresh:product];
    }
    else
    {
        [collectsuit setTitle:@"配装收藏" forState:UIControlStateNormal];
        product = [[DataManager sharedManager] getFavoriteProducts:KeyFilter  Shopid:shopid];
        isclick = NO;
        [self newfresh:product];
    }
}

- (void)updatePage:(UIScrollView *)scrollview{
    if (numtag==2) {
    int page1 = scrollview.contentOffset.x/scrollview.width;
    //    int idx = 0;
    //    for (SuitView *suit in suitView_) {
    //        if (idx==page) {
    //
    //            [suit loadImage];
    //        }else{
    //            [suit unloadImage];
    //        }
    //        idx ++;
    //    }
    
    for (int i = 0; i < product.count; i++) {
        SuitView *suit = (SuitView *)[scroll viewWithTag:10000+i];
        if (i==page1) {
            if (1) {
                
                for (int j = -1; j < 2; j++) {
                    
                    
                    if ((i+j)<0 || (i+j)>=product.count) {
                        continue;
                    }
                    
                    suit = (SuitView *)[scroll viewWithTag:10000+i+j];
                    if (suit) {
                        continue;
                    }
                    
                    SuitObject *obj = [product objectAtIndex:i+j];
                    SuitView *s = [[SuitView alloc] initWithSuitObject:obj frame:CGRectMake(0, 0, 320, scroll.height)];
                    [scroll addSubview:s];
                    s.center = CGPointMake(scroll.width/2 + scroll.width * (i+j), scroll.height/2);
                    s.tag = 10000+i+j;
                    
                    [s unloadImage];
                }
            }
            suit = (SuitView *)[scroll viewWithTag:10000+i];
            [suit loadImage];
        }else{
            
            if (i<page1-1||i>page1+1) {
                SuitView *suit = (SuitView *)[scroll viewWithTag:10000+i];
                if (suit) {
                    [suit removeFromSuperview];
                }
                
            }
            else if(i==page1-1||i==page1+1)
            {
                SuitView *suit = (SuitView *)[scroll viewWithTag:10000+i];
                suit.contentOffset = CGPointMake(0, 0);
            }
            
            [suit unloadImage];
        }
    }
    }
}

#pragma mark 更新配装
-(void)suitFilterRefresh1:(NSNotification *)sender
{
    
    NSDictionary* dic =  sender.object;
    
    KeyObject* key = [dic objectForKey:@"key"];
    
    [KeyFilter replaceObjectAtIndex:[[dic objectForKey:@"category"]intValue]-301 withObject:key];
    
    [self updateKeyButton:[[dic objectForKey:@"category"]intValue]-300];
    
    [self getRefreshProduct];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}
-(void)filterRefresh{
    [scroll removeFromSuperview];
    product = [[DataManager sharedManager] getSuitArrayByFilter:KeyFilter insuit:NO];
    
    float offset = 45;
    UIImage *suitBG = [[UIHelper getInstance] getBundleImage:@"suitView_bg.png"];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(offset, 64, 1024-offset*2, suitBG.size.height)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(offset, 0, 1024-offset*2, suitBG.size.height)];
    }
    [self.view addSubview:scroll];
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.backgroundColor = [UIColor clearColor];
   // scroll.center = CGPointMake(1024/2, (748-44)/2);
    scroll.clipsToBounds = NO;
    scroll.delegate = self;
    
    //    float cWidth = 0;
    
    //    suitView_ = [NSMutableArray array];
    //    for (int i = 0; i < suits_.count; i++) {
    //        SuitObject *obj = [suits_ objectAtIndex:i];
    //        SuitView *s = [[SuitView alloc] initWithSuitObject:obj];
    //
    //        [suitView_ addObject:s];
    //
    //        [scroll addSubview:s];
    //        s.center = CGPointMake(scroll.width/2 + scroll.width * i, scroll.height/2);
    //        cWidth = s.right;
    //    }
    
    [self updatePage:scroll];
    
    scroll.contentSize = CGSizeMake(scroll.width * product.count, scroll.height);
    scroll.pagingEnabled = YES;

}
-(void)showtip:(NSNotification *)sender
{
    NSArray *tips = [[DataManager sharedManager]getTipsarray];
    if (tips.count==0) {
        return;
    }
    NSDictionary *tipdic = [tips objectAtIndex:tips.count-1];
    
    [self performSelectorOnMainThread:@selector(addTipView:) withObject:tipdic waitUntilDone:YES];
    
}

- (void)addTipView:(NSDictionary *)dic{
    TipView *tipview = [[TipView alloc]initWithdic:dic];
    [self.navigationController.view addSubview:tipview];
}

-(void)refreshstatistic:(NSNotification *)sender
{
    [self getRefreshProduct];
}

-(void)detail1:(NSNotification *)sender
{
    SuitObject *suit = sender.object;
    SuitDetailViewController *detail = [[SuitDetailViewController alloc]initWithNibName:nil bundle:nil obj:suit];
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)detail2:(NSNotification *)notification{
    // [self.navigationController.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    // [search removeFromSuperview];
    ProductObject *obj = (ProductObject *)notification.object;
    ProductDetailViewControllerEx *detail = [[ProductDetailViewControllerEx alloc] initWithProduct:obj];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark 配装图片点击弹出大图
- (void)suitImageClicked:(NSNotification *)notification{
    
    SuitObject *obj = notification.object;
    
    NSString * path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pic_path];
    NSArray *array = [NSArray arrayWithObject:path];
    PictureViewController *pic = [[PictureViewController alloc] initWithPictures:array withFrame:self.view.frame Desc:obj.c_miaos];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:pic];
    UIImage *img = [[PMGlobal getInstance]getnavigationbarimage];
    [nav.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];

    [self.navigationController presentModalViewController:nav animated:YES];
    
}

-(void)removecancelled
{
    NSArray *cancelledproducts = [[DataManager sharedManager] getCanceledOrderProducts:KeyFilter  Shopid:shopid];
    for (int i=0; i<cancelledproducts.count; i++) {
        ProductObject *productobj = [cancelledproducts objectAtIndex:i];
        ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
        OrderObject *cancelledorder = [[DataManager sharedManager]createOrderByProduct:productobj ShopId:shopobj.shopID];
        [cancelledorder clearOrder];
        [[DataManager sharedManager]deleteOrderItem:cancelledorder withSizeNo:nil withTableName:@"g_meeting" Shopid:shopobj.shopID];
        sizeType = [[DataManager sharedManager] getSizeTypeBySizeGroup:productobj.pSizeGroupID];
        sizegroupid = [[DataManager sharedManager] getSizeListBySizeGroup:productobj.pSizeGroupID SizeType:[sizeType objectAtIndex:0]];
        SizeObject *sizeobject = [sizegroupid objectAtIndex:0];
        [cancelledorder setOrder:sizeobject.sSizeNo withQuantity:0 withShopID:shopid];
        [[DataManager sharedManager]placeOrder:cancelledorder];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"numreload" object:productobj];
    }
    [self submitbyself];
}

-(void)ordernumrefresh1:(NSNotification *)sender
{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
//    unsubproducts = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
    
    int c = [[DataManager sharedManager] getUnloadProduct:shopobj.shopID];
    NSString *str1 = [NSString stringWithFormat:@"%d",c];
    if (c==0) {
        unsubcount.hidden = YES;
    }
    else
    {
        unsubcount.hidden = NO;
        unsubcount.text = str1;
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}

-(void)ordernumrefresh:(NSNotification *)sender{
    [[AppManager sharedManager]setSubmitStatus:NO];
    [self getRefreshProduct];
    
    [self ordernumrefresh1:sender];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField becomeFirstResponder];
    return YES;
}

-(void)setOrdercount:(int)count
{

    NSString *countstr = [NSString stringWithFormat:@"订单管理(%d)",count];
    [self setNavTitle:countstr];
}
@end
